﻿module Sustainalytics.Controversies {

    angular.module(controversiesModuleName).directive('scatterChart', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                incidents: '=',
                select: '&'
            },
            template: '<div class="scatterChart"></div>',

            controller: ['$scope', '$filter', function ($scope, $filter) {

                $scope.height = '200px';
                $scope.width = '800px';

                $scope.data = [];

                if ($scope.incidents) {

                    var sortedIncidents: IncidentDto[] = [];

                    var hasMainScore = false;

                    for (var i = 0; i < $scope.incidents.length; i++) {
                        var incident = $scope.incidents[i];
                        if (incident.isMainIncident && !hasMainScore) {
                            hasMainScore = true;
                        }
                        else {
                            incident.isMainIncident = false;
                        }
                        sortedIncidents.push(incident);
                    }

                    sortedIncidents.sort(function (incident1, incident2) {
                        var date1 = new Date(incident1.incidentDate);
                        var date2 = new Date(incident2.incidentDate);
                        return date1.getTime() - date2.getTime();
                        //return (date1.incidentDate > date2.incidentDate) ? 1 : (date1.incidentDate < date2.incidentDate) ? -1 : 0;
                    });

                    var minDate = new Date();
                    minDate.setMonth(minDate.getMonth() - 36);

                    var minDateFormated = $filter('date')(minDate, 'MMM dd yyyy');

                    $scope.data.push({
                        'date': minDateFormated,
                        'datetext': $filter('date')(minDate, 'yyyy-MM-dd'),
                        'score': -1,
                        'mainScore': -1,
                        'balloonText': '',
                        'id': null,
                        'incidentId': null,
                        'incidentName': ''
                    });

                    $.each(sortedIncidents, function (index, incident) {

                        var incidentDate = new Date(incident.incidentDate);

                        if ((incidentDate.getTime() >= minDate.getTime())) {

                            var date = $filter('date')(incidentDate, 'MMM dd yyyy');

                            var score = Math.max(incident.impactScore, incident.riskScore);

                            var mainScore = -1;
                            if (incident.isMainIncident) {
                                mainScore = score;
                            }

                            var balloonText = incident.name;
                            if (incident.type == 1 || incident.type == 2) {
                                balloonText = 'UPDATE ' + incident.name;
                            }

                            $scope.data.push({
                                'date': date,
                                'datetext': $filter('date')(incidentDate, 'yyyy-MM-dd'),
                                'score': score,
                                'mainScore': mainScore,
                                'balloonText': balloonText,
                                'id': incident.id,
                                'incidentId': incident.incidentId,
                                'incidentName': incident.name
                            });
                        }
                    });

                    var currentDateFormated = $filter('date')(new Date(), 'MMM dd yyyy');

                    $scope.data.push({
                        'date': currentDateFormated,
                        'datetext': $filter('date')(new Date(), 'yyyy-MM-dd'),
                        'score': -1,
                        'mainScore': -1,
                        'balloonText': '',
                        'id': null,
                        'incidentId': null,
                        'incidentName': ''
                    });

                }
            }],

            link: function ($scope, element) {

                // use existing outer id to create new id
                var id = element[0].id;
                element.attr('id', id);
                var chart;

                var onClick = function (event) {
                    var incident = new IncidentDto();
                    incident.id = event.item.dataContext.id;
                    incident.incidentId = event.item.dataContext.incidentId;
                    incident.name = event.item.dataContext.incidentName;

                    // call external scope's function
                    $scope.select({ incident: incident });

                    //console.log(event.item.dataContext);
                };

                var renderChart = function (options) {

                    element.css({
                        'height': $scope.height,
                        'width': $scope.width
                    });

                    //chart = new AmCharts.AmXYChart(null);
                    chart = new AmCharts.AmSerialChart(null);

                    // listen for click event and call "onClick" method then it happens
                    chart.addListener("clickGraphItem", onClick);

                    chart.dataDateFormat = 'YYYY MM DD';

                    chart.autoMargins = true;
                    chart.marginTop = 0;
                    chart.marginLeft = 0;
                    chart.marginBottom = 0;
                    chart.marginRight = 0;
                    //chart.pathToImages = options.pathToImages;
                    
                    chart.fontFamily = 'Calibri';
                    chart.fontSize = 13;

                    // default animation length
                    chart.startDuration = 0.5;
                    chart.sequencedAnimation = false;

                    chart.dataProvider = $scope.data;


                    chart.categoryField = 'datetext';

                    // Set Category Axis Properties

                    var categoryAxis = chart.categoryAxis;
                    if (categoryAxis) {
                        //categoryAxis.labelOffset = 20;
                        categoryAxis.gridCount = 7;
                        //categoryAxis.centerLabelOnFullPeriod = true;
                        categoryAxis.parseDates = true;
                        categoryAxis.equalSpacing = false;
                        categoryAxis.autoGridCount = false;
                        categoryAxis.gridPosition = 'start';
                        //categoryAxis.tickLength = -1;
                        //categoryAxis.minPeriod = 'YYYY';
                        categoryAxis.autoWrap = true;
                        chart.categoryAxis = categoryAxis;
                    }


                    // Create value axis

                    var valueAxis = new AmCharts.ValueAxis();
                    valueAxis.baseValue = 0;
                    valueAxis.minimum = 0;
                    valueAxis.maximum = 11;
                    valueAxis.step = 2;
                    valueAxis.minMaxMultiplier = 10;
                    valueAxis.precision = 0;
                    valueAxis.title = 'Score';
                    valueAxis.showFirstLabel = false;
                    valueAxis.showLastLabel = false;
                    valueAxis.autoGridCount = false;
                    valueAxis.gridCount = 10;

                    chart.addValueAxis(valueAxis);


                    // create the graphs
                    var graph1 = new AmCharts.AmGraph();
                    graph1.valueField = 'score';
                    graph1.title = 'Incident';
                    graph1.bullet = 'round';
                    graph1.bulletColor = '#000000';
                    graph1.fillColors = '#23b1a5';
                    graph1.lineAlpha = 0;
                    graph1.lineThickness = 1;
                    //graph1.balloonText = '<span style="font-size:14px">[[category]]: <b>[[value]]</b></span>';
                    graph1.balloonText = "[[balloonText]]";
                    chart.addGraph(graph1);


                    var graph2 = new AmCharts.AmGraph();
                    graph2.valueField = 'mainScore';
                    graph2.title = 'Main incident';
                    graph2.bullet = 'round';
                    graph2.bulletSize = 16;
                    graph2.bulletAlpha = 0;
                    graph2.bulletBorderAlpha = 1;
                    graph2.bulletBorderColor = '#791200';
                    graph2.bulletColor = '#FFFFFF';
                    graph2.fillColors = '#9400D3';
                    graph2.lineAlpha = 0;
                    graph2.lineThickness = 1;
                    graph2.balloonText = '';

                    chart.addGraph(graph2);


                    var chartCursor = new AmCharts.ChartCursor();
                    
                    //chartCursor.categoryBalloonDateFormat = 'MMM DD YYYY';

                    chart.addChartCursor(chartCursor);

                    chart.write(id);
                };

                // Render the chart
                renderChart($scope.options);

                // amCharts events

                $scope.$on('amCharts.triggerChartAnimate', function (event, id) {
                    if (id === element[0].id || !id) {
                        chart.animateAgain();
                    }
                });

                $scope.$on('amCharts.updateData', function (event, data, id) {
                    if (id === element[0].id || !id) {
                        chart.dataProvider = data;
                        chart.validateData();
                    }
                });

                $scope.$on('amCharts.validateNow', function (event, validateData, skipEvents, id) {
                    if (id === element[0].id || !id) {
                        chart.validateNow(validateData === undefined ? true : validateData,
                            skipEvents === undefined ? false : skipEvents)
                    }
                });
                
                $scope.$on('amCharts.renderChart', function (event, amChartOptions, id) {
                    if (id === element[0].id || !id) {
                        renderChart(amChartOptions);
                    }
                });

                $scope.$on('amCharts.clickGraphItem', function (event, amChartOptions, id) {
                    if (id === element[0].id || !id) {
                        //renderChart(amChartOptions);
                    }
                });
            }

        };
    });
}